#pragma once

#include <iostream>
#include <string>
#include <vector>
#include <fstream>
#include <algorithm>
#include <mutex>
#include <cassert>

#include "../comm/log.hpp"
#include "../comm/util.hpp"
#include "oj_model.hpp"
#include "oj_view.hpp"

namespace ns_control
{
    using namespace std;
    using namespace ns_util;
    using namespace ns_log;
    using namespace ns_model;
    using namespace ns_view;
    using namespace httplib;

    const std::string machine_conf = "./conf/service_machine.conf";

    // 提供服务的主机
    class Machine
    {
    public:
        std::string ip;    // 编译服务的ip
        int port;          // 编译服务的端口
        uint64_t load;     // 编译服务的负载
        std::mutex *mtx;  // mutex禁止拷贝，使用指针
    public:
        Machine() : ip(""), port(0), load(0), mtx(nullptr)
        {}
        ~Machine() {}
    public:    
        // 增加主机负载
        void IncLoad()
        {
            if (mtx) mtx->lock();
            load++;
            if (mtx) mtx->unlock();
        }
        // 减少主机负载
        void DecLoad()
        {
            if (mtx) mtx->lock();
            load--;
            if (mtx) mtx->unlock();
        }
        void ResetLoad()
        {
            if (mtx) mtx->lock();
            load = 0;
            if (mtx) mtx->unlock();
        }
        uint64_t Load()
        {
            uint64_t _load = 0;
            if (mtx) mtx->lock();
            _load = load;
            if (mtx) mtx->unlock();

            return _load;
        }
    };

    // 负载均衡模块
    class LoadBalance
    {
    private:
        // 可以给我们提供编译服务的所有的主机
        // 每一台主机都有自己的下标，充当当前主机的id
        std::vector<Machine> machines; 
        // 所有在线的主机id
        std::vector<int> online;
        // 所有离线的主机id
        std::vector<int> offline;
        // 保证LoadBalance的数据安全
        std::mutex mtx;
    public:
        LoadBalance() 
        {
            assert(LoadConf(machine_conf));
            LOG(INFO) << "加载: " << machine_conf << "成功" << "\n";

        }
        ~LoadBalance() {}
    public:
        bool LoadConf(const std::string &machine_conf)
        {
            ifstream in(machine_conf);
            if (!in.is_open()) {
                LOG(FATAL) << "加载: " << machine_conf << "失败" << "\n";
                return false;
            }

            std::string line;
            while(getline(in, line))
            {
                vector<string> tokens;
                StringUtil::StringSpilt(line, &tokens, ":");
                if(tokens.size() != 2)
                {
                    LOG(WARNING) << "切分" << line << "失败" << "\n";
                    continue;
                }
                Machine machine;
                machine.ip = tokens[0];
                machine.port = stoi(tokens[1]);
                machine.mtx = new mutex;

                online.push_back(machines.size());
                machines.push_back(machine);
            }

            in.close();
            return true;
        }
        // 输出型参数
        bool SmartChoice(int *id, Machine **m)
        {
            // 1. 使用选择好的主机（更新主机的负载）
            // 2. 可能需要离线该主机
            mtx.lock();
            // 负载均衡算法：采用轮询+hash
            int online_num = online.size();
            if (online_num == 0)
            {
                mtx.unlock();
                LOG(FATAL) << "所有的后端编译服务主机离线！" << "\n";
                return false;
            }

            *id = online[0];
            *m = &machines[online[0]];
            uint64_t min_load = machines[online[0]].Load();
            for (int i = 0; i < online_num; i++)
            {
                uint64_t curr_load = machines[online[i]].Load();
                if (min_load > curr_load)
                {
                    min_load = curr_load;
                    *id = online[i];
                    *m = &machines[online[i]];
                }
            }

            mtx.unlock();
            return true;
        }

        void OnlineMachine()
        {
            // 统一上线
            mtx.lock();
            online.insert(online.end(), offline.begin(), offline.end());
            offline.erase(offline.begin(), offline.end());

            mtx.unlock();

            LOG(INFO) << "所有主机又上线了！" << "\n";
        }
        
        void OfflineMachine(int which)
        {
            mtx.lock();
            for (auto iter = online.begin(); iter != online.end(); iter++)
            {
                if (*iter == which)
                {
                    machines[which].ResetLoad();
                    online.erase(iter);
                    offline.push_back(which);
                    break;
                }
            }
            mtx.unlock();
        }

        // for test
        void ShowMachine()
        {
            mtx.lock();
            std::cout << "当前在线主机列表：";
            for (auto &id: online)
            {
                std::cout << id << " ";
            }
            std::cout << std::endl;
            std::cout << "当前离线主机列表：";
            for (auto &id: offline)
            {
                std::cout << id << " ";
            }
            std::cout << std::endl;
            mtx.unlock();

        }
    };

    // 核心业务逻辑控制器
    class Control
    {
    private:
        Model model_; // 提供后台数据
        View view_;   // 提供网页渲染
        LoadBalance load_balance_;  // 负载均衡器
    public:
        Control() {}
        ~Control() {}
    public:
        void RecoverMachine()
        {
            load_balance_.OnlineMachine();
        }

        // 根据题目数据构建网页
        // html: 输出型参数
        bool AllQuestions(string *html)
        {
            bool ret = true;
            vector<ns_control::Question> all;
            if (model_.GetAllQuestion(&all))
            {
                sort(all.begin(), all.end(), [](const struct Question &q1, const struct Question &q2){
                    return stoi(q1.number) < stoi(q2.number);
                });
                // 获取题目信息成功，将所有的题目数据构建成网页
                view_.AllExpandHtml(all, html);
            }
            else
            {
                ret = false;
                *html = "获取题目失败，形成题目列表失败";
            }

            return ret;
        }

        bool Question(const string &number, string *html)
        {
            bool ret = true;
            ns_control::Question q;
            if (model_.GetOneQuestion(number, &q))
            {
                view_.OneExpandHtml(q, html);
            }
            else 
            {
                ret = false;
                *html = "指定题目：" + number + "不存在";
            }
            
            return ret;
        }

        // code: #include
        // input: ""
        void Judge(const std::string &number, const std::string &in_json, std::string *out_json)
        {
            //LOG(DEBUG) << in_json << "\nnumber:" << number << "\n";
            // 0. 根据题目编号，直接拿到对应的题目细节
            struct Question q;
            model_.GetOneQuestion(number, &q);

            // 1. in_json进行反序列化，得到题目的id，得到用户提交的源代码，input
            Json::Value in_value;
            if (!JsonUtil::deserialize(in_json, in_value)) {
                return;
            }
            std::string code = "#define COMPILER_ONLINE 1\n";
            code += in_value["code"].asString();

            // 2. 重新拼接用户代码+测试用例代码，形成新的代码
            Json::Value compile_value;
            compile_value["input"] =  in_value["input"].asString();
            compile_value["code"] = code + "\n" + q.tail;
            compile_value["cpu_limit"] = q.cpu_limit;
            compile_value["mem_limit"] = q.mem_limit;

            std::string compile_json;
            JsonUtil::serialize(compile_value, &compile_json);

            // 3. 选择负载最低的主机 (差错处理)
            // 规则：一直选择，直到主机可用，否则，全部挂掉
            while (true)
            {
                int id = -1;
                Machine* m = nullptr;
                if (!load_balance_.SmartChoice(&id, &m)) {
                    break;
                }

                // 4. 发起http请求，得到结果
                Client cli(m->ip, m->port);
                m->IncLoad();
                LOG(INFO) << "选择主机成功，主机id：" << id << "，详情: "<< m->ip << ":" << m->port << " 负载: " << m->Load() << "\n";
                if (auto res = cli.Post("/compile_and_run", compile_json, "application/json; charset=utf-8"))
                {
                    // 5. 结果赋值给out_json
                    //LOG(DEBUG) << "status: " << res->status <<"\n";
                    if (res->status == 200) 
                    {
                        *out_json = res->body;
                        m->DecLoad();
                        LOG(INFO) << "请求编译和运行服务成功..." << "\n";
                        break;
                    }
                    m->DecLoad();
                }
                else
                {
                    // 请求失败
                    LOG(ERROR) << "当前主机的id：" << id << "，详情: " << m->ip << ":" << m->port << "可能离线" << "\n";
                    m->DecLoad();
                    load_balance_.OfflineMachine(id);
                    load_balance_.ShowMachine();
                }
            }  
            
        }
    };
}